const { getApiUrl } = require('../../config/config')
const { formatTime, formatDate } = require('../../utils/util')

Page({
  data: {
    days: 'null', // 默认查询全部历史数据
    pageSize: 10,
    currentPage: 1,
    followers: [],
    totalFollowers: 0,
    isLoading: false,
    hasMore: true,
    userId: null,
    dayOptions: [
      { value: 'null', text: '全部' },
      { value: '7', text: '最近7天' },
      { value: '30', text: '最近30天' },
      { value: '90', text: '最近90天' }
    ],
    showFilter: false,
    dayFilterText: '全部',
    refreshing: false,
    animationData: {},
    showBackToTop: false,
    scrollTop: 0
  },

  onLoad: function() {
    // 设置导航栏
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#ff6b6b'
    });
    
    // 初始化动画实例
    this.animation = wx.createAnimation({
      duration: 300,
      timingFunction: 'ease',
    });
    
    const userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      this.setData({ userId: userInfo.id });
      this.fetchFollowers();
    } else {
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        success: () => {
          setTimeout(() => {
            wx.redirectTo({ url: '/pages/login/login' });
          }, 1500);
        }
      });
    }

    // 创建页面滚动监听器
    this.createIntersectionObserver()
      .relativeToViewport()
      .observe('.follow-item', (res) => {
        // 为出现在视图中的元素添加动画标记
        if (res.intersectionRatio > 0) {
          const index = res.dataset.index;
          const key = `followers[${index}].animation`;
          this.setData({
            [key]: true
          });
        }
      });
  },

  onShow: function() {
    // 如果页面展示，检查是否需要重新加载数据
    if (this.data.needRefresh) {
      this.resetAndFetch();
      this.setData({ needRefresh: false });
    }
  },

  onPullDownRefresh: function() {
    this.setData({ refreshing: true });
    
    // 创建下拉刷新动画效果
    setTimeout(() => {
      this.resetAndFetch();
      setTimeout(() => {
        this.setData({ refreshing: false });
        wx.stopPullDownRefresh();
        // 显示成功提示
        wx.showToast({
          title: '刷新成功',
          icon: 'success',
          duration: 1500
        });
      }, 600);
    }, 800);
  },

  onReachBottom: function() {
    if (this.data.hasMore && !this.data.isLoading) {
      this.loadMoreData();
    }
  },

  // 监听页面滚动事件
  onPageScroll: function(e) {
    // 保存滚动位置
    this.setData({
      scrollTop: e.scrollTop,
      showBackToTop: e.scrollTop > 300 // 滚动超过300px显示回到顶部按钮
    });
  },

  // 回到顶部
  scrollToTop: function() {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    });
    
    if (wx.vibrateShort) {
      wx.vibrateShort({ type: 'light' });
    }
  },

  // 页面点击事件，用于关闭筛选框
  onTap: function() {
    if (this.data.showFilter) {
      this.setData({ showFilter: false });
    }
  },

  // 显示/隐藏筛选选项
  toggleFilter: function() {
    this.setData({
      showFilter: !this.data.showFilter
    });
    
    if (wx.vibrateShort) {
      wx.vibrateShort({ type: 'light' });
    }
  },

  // 选择天数筛选
  selectDayFilter: function(e) {
    const { value, text } = e.currentTarget.dataset;
    if (value === this.data.days) {
      this.setData({ showFilter: false });
      return;
    }
    
    this.setData({
      days: value,
      dayFilterText: text,
      showFilter: false
    });
    
    // 添加一个轻微的触感反馈
    if (wx.vibrateShort) {
      wx.vibrateShort({ type: 'light' });
    }
    
    this.resetAndFetch();
  },

  // 重置并重新加载数据
  resetAndFetch: function() {
    this.setData({
      currentPage: 1,
      hasMore: true,
      followers: [],
      totalFollowers: 0
    });
    this.fetchFollowers();
  },

  // 加载更多数据
  loadMoreData: function() {
    if (!this.data.hasMore || this.data.isLoading) return;
    
    const nextPage = this.data.currentPage + 1;
    this.setData({
      currentPage: nextPage
    });
    this.fetchFollowers();
  },

  // 获取新增关注数据
  fetchFollowers: function() {
    const { userId, days, currentPage, pageSize } = this.data;

    if (!userId) return;

    this.setData({ isLoading: true });

    wx.request({
      url: getApiUrl('/message/new-followers'),
      method: 'GET',
      data: {
        userId: userId,
        days: days === 'null' ? null : days,
        page: currentPage,
        size: pageSize
      },
      success: (res) => {
        if (res.data.code === 200) {
          const newData = res.data.data;
          
          // 处理日期显示和关注状态
          if (newData.followers && newData.followers.length > 0) {
            newData.followers.forEach((item, index) => {
              // 确保每个item都有唯一ID
              item.id = item.id || `follower_${Date.now()}_${index}`;
              item.formattedDate = this.getDisplayDate(item.createTime);
              item.formattedTime = this.getSimpleDate(item.createTime);
              
              // 默认设置为未关注状态，实际应该从服务器获取
              // 这里仅作为演示，实际项目中应该调用API判断是否已关注
              item.isFollowing = false;
              
              // 添加动画属性
              item.animation = false;
            });
          }
          
          // 合并数据
          let updatedFollowers;
          if (this.data.currentPage === 1) {
            // 首次加载
            updatedFollowers = newData.followers || [];
          } else {
            // 加载更多，合并数据
            // 防止数据重复，先过滤掉已有的数据
            const existingIds = new Set(this.data.followers.map(item => item.id));
            
            const newFollowers = newData.followers.filter(item => !existingIds.has(item.id));
            
            updatedFollowers = [...this.data.followers, ...newFollowers];
          }
          
          // 检查是否还有更多数据可加载
          const hasMore = newData.followers && newData.followers.length === pageSize;
          
          this.setData({
            followers: updatedFollowers,
            totalFollowers: newData.total || 0,
            hasMore: hasMore
          });

          // 添加显示动画延迟
          setTimeout(() => {
            const animatedFollowers = this.data.followers.map((item, index) => {
              if (index < this.data.currentPage * this.data.pageSize) {
                item.animation = true;
              }
              return item;
            });
            
            this.setData({
              followers: animatedFollowers
            });
          }, 100);
          
        } else {
          wx.showToast({
            title: res.data.message || '获取数据失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
        console.error('获取关注列表失败:', err);
      },
      complete: () => {
        this.setData({ isLoading: false });
      }
    });
  },

  // 关注/取消关注
  toggleFollow: function(e) {
    const { index, userId, isFollowing } = e.currentTarget.dataset;
    const action = isFollowing ? '取消关注' : '关注';
    
    // 添加触感反馈
    if (wx.vibrateShort) {
      wx.vibrateShort({ type: 'medium' });
    }
    
    // 先更新UI状态，优化体验
    const followKey = `followers[${index}].isFollowing`;
    this.setData({
      [followKey]: !isFollowing
    });
    
    // API调用逻辑
    const apiUrl = getApiUrl(isFollowing ? '/user/unfollow' : '/user/follow');
    
    wx.request({
      url: apiUrl,
      method: 'POST',
      data: {
        userId: this.data.userId,
        followUserId: userId
      },
      success: (res) => {
        if (res.data.code !== 200) {
          // 如果失败，回滚状态
          this.setData({
            [followKey]: isFollowing
          });
          
          wx.showToast({
            title: `${action}失败：${res.data.message}`,
            icon: 'none'
          });
        } else {
          // 显示成功提示
          wx.showToast({
            title: `${action}成功`,
            icon: 'success',
            duration: 1500
          });
        }
      },
      fail: (err) => {
        // 网络失败，回滚状态
        this.setData({
          [followKey]: isFollowing
        });
        
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
        console.error(`${action}失败:`, err);
      }
    });
  },

  // 跳转到用户主页
  goToUserProfile: function(e) {
    const userId = e.currentTarget.dataset.userId;
    if (userId) {
      wx.navigateTo({
        url: `/pages/user/user?userId=${userId}`
      });
    }
  },

  // 格式化日期
  getDisplayDate: function(timestamp) {
    if (!timestamp) return '';
    return formatDate(new Date(timestamp));
  },

  // 简化的时间显示
  getSimpleDate: function(timestamp) {
    if (!timestamp) return '';
    
    const now = new Date();
    const date = new Date(timestamp);
    const diff = Math.floor((now - date) / 1000); // 秒数差
    
    if (diff < 60) {
      return '刚刚';
    } else if (diff < 3600) {
      return `${Math.floor(diff / 60)}分钟前`;
    } else if (diff < 86400) {
      return `${Math.floor(diff / 3600)}小时前`;
    } else if (diff < 604800) {
      return `${Math.floor(diff / 86400)}天前`;
    } else {
      return formatDate(date);
    }
  }
}); 